package com.edee.bigday.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class BigdayFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //RequestContextHolder.currentRequestAttributes();
                //可以利用RequestContextHolder拿到刚进来的请求数据：
                //同时，将RequestAttributes强转为：ServletRequestAttributes，
                // 因为后者最终实现的是RequestAttributes接口。 --------即：每次请求进来，就先拦截下来，将老请求的cookie同步给新请求（结合：com/edee/bigday/member/web/MemberWebController.java）。
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    System.out.println("RequestInterceptor线程--" + Thread.currentThread().getId());
                    //获取原请求（老请求）：
                    HttpServletRequest request = requestAttributes.getRequest();
                    //System.out.println("Feign远程调用之前，先调用RequestInterceptor的apply()方法。");
                    if (request != null) {
                        //同步请求头数据，主要是cookie：
                        String cookie = request.getHeader("Cookie");
                        //为新请求template设置原请求的Cookie（给新请求同步了老请求的cookie）：
                        template.header("Cookie", cookie);
                    }
                }
            }
        };
    }
}
